<?

	include("inc/config.inc.php");

	$a = mysqli_real_escape_string($con,$_GET[a]);
	$r = mysqli_real_escape_string($con,$_GET[r]);

	// Check user is manager
	if ($_SESSION[role] != "Manager" && $_SESSION[role] != "HR")
		die("Error 31 - Role assignment error - Please contact  support.");

	// Check valid options are passed
	if ($a != "Rejected" && $a != "Accepted" || !is_numeric($r))
		die("Error 32 - Parameter error - Please contact support.");

	// Grab details of the request
	$result = mysqli_query($conn, "SELECT requests.user, requests.startdate, requests.starttime, requests.enddate, requests.endtime, requests.description, requests.requestid, users.email, users.manager FROM users, requests WHERE (users.user = requests.user) AND requests.requestid='$r' AND users.manager='$_SESSION[user]' AND requests.status='pending';");
	if (mysqli_num_rows($result) > 0)
	{
		$request = mysqli_fetch_array($result);
		if ($_SESSION[user] != $request[manager])
			die("Error 33 - User selection error - Please contact support.");
		
		else
		{
			// Human dates
			$startdate = date("d-m-Y", strtotime($request[startdate]));
		        $enddate = date("d-m-Y", strtotime($request[enddate]));

			niceMail($request[email], "Holiday request ". strToLower($a), "Your holiday request has been ". strToLower($a) ." by $_SESSION[user].\n\rFrom: $startdate ($request[starttime])\rTo: $enddate ($request[endtime])\rDescription: $request[description]\n\rVisit " . $config[url] . " for full details");

			// Outlook/iCal calendar invite to requestee
			if ($request[starttime] == "am") $icalsTime = "T090000Z";
			if ($request[starttime] == "pm") $icalsTime = "T123000Z";
			if ($request[endtime] == "am") $icaleTime = "T123000Z";
			if ($request[endtime] == "pm") $icaleTime = "T173000Z";
			$icalStart = date("Ymd", strtotime($request[startdate])) . $icalsTime;
			$icalEnd = date("Ymd", strtotime($request[enddate])) . $icaleTime;
			$managerEmail = getManagerEmail($request[user]);
			sendCalendar($request[email], $request[description], $icalStart, $icalEnd, ""); // Requester
			sendCalendar($managerEmail, $request[description], $icalStart, $icalEnd, $request[user]); // Manager

			// Update request in database
			mysqli_query($conn, "UPDATE requests SET status='$a', statusdate=now(), statusmessage='$a by $_SESSION[user]' WHERE requestid='$r'");

			// Redirect to main page when there are no more requests
			if (getWaitingApprovalsCount() == 0)
				header("Location:main.php");
			else
				header("Location:approvals.php");
		}
		
	}
	else
		die("Error 34 - Request error - Please contact support.");

?>
